package fragment;


import android.content.Entity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.qianfeng.lingshijia.R;
import com.qianfeng.lingshijia.SecKillActivity;
import com.qianfeng.lingshijia.WebViewActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import adapter.HotSaleAdapter;
import adapter.ImportListAdapter;
import adapter.SaleListAdapter;
import adapter.StockpileAdapter;
import custom.HeadViewPager;
import custom.ImportView;
import custom.MyGridView;
import custom.NavTypeView;
import entity.HeadEntity;
import entity.HotSaleEntity;
import utils.Constants;
import utils.DownloadUtils;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {

    //头部viewpager
    HeadViewPager headViewPager;
    //特惠马上抢
    GridView saleList_Grid;
    SaleListAdapter saleListAdapter;
    //秒杀
    ImageView secKillPic;
    TextView secKillTitle,secKillPrice;
    HeadEntity.DataEntity.SeckillProductEntity secKillEntity;


    //囤货必备
    GridView stockpile_Grid;
    StockpileAdapter stockpileAdapter;

    private TextView  hoursTv, minutesTv, secondsTv;//时分秒显示的view
    private long time=System.currentTimeMillis();

    private long mHour =0;
    private long mMin = 0;
    private long mSecond =0;// 小时,分钟,秒
    private boolean isRun = true;

    //导航条
    private NavTypeView oddsView, stockpileView,importView,deserveView,hotView;
    private ImportView id_impoet_item;

    //进口散装
    ImportListAdapter importListAdapter;

    //热销单品
    HotSaleAdapter hotSaleAdapter;
    //上下拉刷新
    int pageNumber = -1;
    PullToRefreshScrollView pullToRefreshScrollView;
    //什么值得买
    HeadEntity.DataEntity.ReportListEntity reportEntity;
    String reportListLink;
    ImageView reportPic;
    TextView reportTitle;

    public HomeFragment()
    {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        loadHeadData();
        loadHotSaleData();
    }

    public void init(View view)
    {
        //导航条

        hoursTv = (TextView) view.findViewById(R.id.hours_tv);
        minutesTv = (TextView) view.findViewById(R.id.minutes_tv);
        secondsTv = (TextView) view.findViewById(R.id.seconds_tv);

        //倒计时文本设置
        TextView colon_time = (TextView) view.findViewById(R.id.id_nav_title);
        colon_time.setText("整点秒杀");

        oddsView = (NavTypeView) view.findViewById(R.id.id_nav_odds);
        oddsView.setData("  特惠马上抢");
        oddsView.setAllUrl("http://cmsproxy.haolingzui.com/todayPromotionProdcuts.do");
        stockpileView = (NavTypeView) view.findViewById(R.id.id_nav_stockpile);
        stockpileView.setData("  囤货必备");
        stockpileView.setAllUrl("http://cmsproxy.haolingzui.com/stockpileProducts.do");
        importView = (NavTypeView) view.findViewById(R.id.id_nav_import);
        importView.setData("  进口散装");
        importView.setAllUrl("http://cmsproxy.haolingzui.com/importBulkProducts.do");
        deserveView = (NavTypeView) view.findViewById(R.id.id_nav_deserve);
        deserveView.setData("  什么值得买");
        deserveView.setAllUrl("http://cmsproxy.haolingzui.com/reportList.do");
        hotView = (NavTypeView) view.findViewById(R.id.id_nav_hot);
        hotView.setData("  热销单品");
        hotView.setAllUrl("http://cmsproxy.haolingzui.com/hotSaleProdcuts.do");

        //头部ViewPager
        headViewPager = (HeadViewPager) view.findViewById(R.id.head_View_Pager);//viewpager

        //特惠马上抢
        saleList_Grid = (GridView) view.findViewById(R.id.salesList);
        saleListAdapter = new SaleListAdapter(getActivity());
        saleList_Grid.setAdapter(saleListAdapter);

        //整点秒杀
         LinearLayout secKillLayout = (LinearLayout) view.findViewById(R.id.seckill_layout);
         secKillLayout.setOnClickListener(this);
         secKillPic = (ImageView) view.findViewById(R.id.secKill_pic);
         secKillTitle = (TextView) view.findViewById(R.id.secKill_title);
         secKillPrice = (TextView) view.findViewById(R.id.secKill_price);
        //整点秒杀倒计时点击事件
        LinearLayout secKill_Time = (LinearLayout) view.findViewById(R.id.id_time_title);
        secKill_Time.setOnClickListener(this);

        //囤货必备
         stockpile_Grid = (GridView) view.findViewById(R.id.stockpileList);
         stockpileAdapter = new StockpileAdapter(getActivity());
        stockpile_Grid.setAdapter(stockpileAdapter);

        //什么值得买
         reportPic = (ImageView) view.findViewById(R.id.reportList_pic);
         reportTitle = (TextView) view.findViewById(R.id.reportList_title);
        //什么值得买点击事件
        LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.reportList_linear);
        linearLayout.setOnClickListener(this);

        //进口散装
        ListView import_listView = (ListView) view.findViewById(R.id.import_ListView);
        importListAdapter = new ImportListAdapter(getActivity());
        import_listView.setAdapter(importListAdapter);

        //热销单品
        MyGridView hotSale_Grid = (MyGridView) view.findViewById(R.id.hotSaleList);
        hotSaleAdapter = new HotSaleAdapter(getActivity());
        hotSale_Grid.setAdapter(hotSaleAdapter);

        //计时
        final Calendar mCalendar=Calendar.getInstance();
        mCalendar.setTimeInMillis(time);
        mHour = 20-mCalendar.get(Calendar.HOUR_OF_DAY);
        mMin = 60-mCalendar.get(Calendar.MINUTE);
        mSecond = 60- mCalendar.get(Calendar.SECOND);
        if(mHour>0 && mMin>0 && mSecond>0){
            // countDown.setVisibility(View.VISIBLE);
        }
        startRun();

        //设置上拉加载，下拉刷新
        pullToRefreshScrollView = (PullToRefreshScrollView) view.findViewById(R.id.pullToRefreshScrollView);
        reflesh(pullToRefreshScrollView);
    }

    /**
     * 刷新设置
     * @param scrollView
     */
    private void reflesh(PullToRefreshScrollView scrollView)
    {
        scrollView.setMode(PullToRefreshBase.Mode.BOTH);
        ILoadingLayout startLabels = scrollView.getLoadingLayoutProxy(true,false);
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("正在载入...");// 刷新时
        startLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

        // 设置上拉刷新文本
        ILoadingLayout endLabels = scrollView.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("正在载入...");// 刷新时
        endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                loadHeadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                loadHotSaleData();
            }
        });
    }


    /**
     * 以下头部数据加载
     */
    private void loadHeadData()
    {
        //头部数据加载
        DownloadUtils.getJson(Constants.URL.HEAD_URL, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response = responseInfo.result;
                if (response != null) {
                    // Log.d("data", "onSuccess() returned: " + response);
                    Gson gson = new Gson();
                    HeadEntity entity = gson.fromJson(response, HeadEntity.class);
                    //viewpager
                    headViewPager.setData(entity.getData().getBannerList());
                    //特惠马上抢
                    saleListAdapter.setData(entity.getData().getSalesList());
                    //整点秒杀
                    secKillEntity = entity.getData().getSeckillProduct();
                    secKillSetData(secKillEntity);

                    //囤货必备
                    stockpileAdapter.setData(entity.getData().getStockpileProductList());

                    //什么值得买
                    reportEntity = entity.getData().getReportList();
                    reportListSetData(reportEntity);

                    //进口散装
                    importListAdapter.setData(entity.getData().getImportBulkProductList());

                    //刷新成功
                    pullToRefreshScrollView.onRefreshComplete();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                pullToRefreshScrollView.onRefreshComplete();
                error.printStackTrace();
            }
        });
    }

    /**
     * 以下热销单品数据加载
     */
    private void loadHotSaleData()
    {
        //调用一次自加一次
        pageNumber ++;
        Toast.makeText(getActivity(), pageNumber + "", Toast.LENGTH_SHORT).show();
        //热销单品数据加载
        RequestParams params = new RequestParams();
        //page=0&pageSize=9&sortOrder=0&sortType=1
        params.addBodyParameter("page",pageNumber+"");
        params.addBodyParameter("pageSize", "9");
        params.addBodyParameter("sortOrder", "0");
        params.addBodyParameter("sortType", "1");
        DownloadUtils.postJson(Constants.URL.HOT_SALE_URL, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String response = responseInfo.result;
                Gson gson = new Gson();
                HotSaleEntity entity = gson.fromJson(response, HotSaleEntity.class);
                if (pageNumber > 0) {
                    hotSaleAdapter.addData(entity.getData().getPList());
                } else {
                    hotSaleAdapter.setData(entity.getData().getPList());
                }
                pullToRefreshScrollView.onRefreshComplete();
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                pullToRefreshScrollView.onRefreshComplete();
                error.printStackTrace();
            }
        }, params);
    }

    /**
     * 建议购买数据设置
     * @param reportEntity
     */
    private void reportListSetData(HeadEntity.DataEntity.ReportListEntity reportEntity)
    {
        DownloadUtils.LoadPicture(reportEntity.getImg1(), reportPic);
        reportTitle.setText(reportEntity.getTitle());
        reportListLink = reportEntity.getLinkUrl();
    }

    /**
     * 秒杀数据设置
     * @param KillEntity
     */
    private void secKillSetData(HeadEntity.DataEntity.SeckillProductEntity KillEntity)
    {
        secKillTitle.setText(KillEntity.getTitle());
        DownloadUtils.LoadPicture(KillEntity.getImgUrl(),secKillPic);
        String price = "¥"+KillEntity.getPriceStr()+"   |   我要吃";
        secKillPrice.setText(price);
    }

    /**
     * 定时器设置
     */
    private final Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg){
            if (msg.what==1) {
                computeTime();
                hoursTv.setText(mHour+"");
                if(mHour<10){
                    hoursTv.setText("0"+mHour);
                }
                minutesTv.setText(mMin+"");
                if(mMin<10){
                    minutesTv.setText("0"+mMin);
                }
                secondsTv.setText(mSecond+"");
                if(mSecond<10){
                    secondsTv.setText("0"+mSecond);
                }
                if (mHour==0&&mMin==0&&mSecond==0) {
                    //  countDown.setVisibility(View.GONE);
                }
            }
        }
    };




    private void startRun() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                while (isRun) {
                    try {
                        Thread.sleep(1000); // sleep 1000ms
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private void computeTime() {
        mSecond--;
        if (mSecond < 0) {
            mMin--;
            mSecond = 59;
            if (mMin < 0) {
                mMin = 59;
                mHour--;
                if (mHour < 0) {
                    // 倒计时结束
                    mHour = 23;
                    // countDown.setVisibility(View.GONE);

                }
            }
        }
    }

    /**
     * 整点秒杀以及什么值得买整个layout的点击事件
     * @param view
     */
    @Override
    public void onClick(View view)
    {
        if (view.getId() == R.id.reportList_linear)
        {
            Intent intent = new Intent(getActivity(), WebViewActivity.class);
            intent.putExtra("url",reportListLink);
            startActivity(intent);
        }else{
            //Toast.makeText(getActivity(), "跳转", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), SecKillActivity.class);
            startActivity(intent);
        }

    }
}
